package com.haoxin.ai_course.modules.sys.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haoxin.ai_course.common.annotation.SysLog;
import com.haoxin.ai_course.common.base.AbstractController;
import com.haoxin.ai_course.common.utils.Constant;
import com.haoxin.ai_course.common.utils.R;
import com.haoxin.ai_course.common.validator.Assert;
import com.haoxin.ai_course.common.validator.ValidatorUtils;
import com.haoxin.ai_course.modules.sys.entity.SysRole;
import com.haoxin.ai_course.modules.sys.entity.SysUser;
import com.haoxin.ai_course.modules.sys.entity.SysUserRole;
import com.haoxin.ai_course.modules.sys.service.SysRoleService;
import com.haoxin.ai_course.modules.sys.service.SysUserRoleService;
import com.haoxin.ai_course.modules.sys.service.SysUserService;

import cn.hutool.core.map.MapUtil;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.AllArgsConstructor;

/**
 * 系统用户
 * 
 */

@RestController
@RequestMapping("/sys/user")
@AllArgsConstructor
public class SysUserController extends AbstractController {

	private final SysUserService sysUserService;
	private final SysUserRoleService sysUserRoleService;
	private final SysRoleService sysRoleService;
	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, Object> params){
		//只有超级管理员，才能查看所有管理员列表
		if(getUserId() != Constant.SUPER_ADMIN){
			params.put("createUserId", getUserId());
		}
		//查询列表数据
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		if(MapUtil.getStr(params,"username") != null){
			queryWrapper
					.like("username",MapUtil.getStr(params,"username"))
					.or()
					.like("mobile",MapUtil.getStr(params,"username"));
		}
		queryWrapper.orderByDesc("create_time");
		IPage<SysUser> sysConfigList = sysUserService.page(mpPageConvert.<SysUser>pageParamConvert(params),queryWrapper);
		return R.ok().put("page", mpPageConvert.pageValueConvert(sysConfigList));
	}
	@RequestMapping("/patientList")
	/**
	 * 患者列表
	 * /usr/local/bin/checkdicom
	 * /srv/dev/src/checkdicom
	 * @param params
	 * @return
	 */
	public R patientList(@RequestParam Map<String, Object> params){
		   Long userId = getUserId();
		if(params.get("userId")!=null) {
			userId = Long.parseLong((String)params.get("userId"));
		}
		//只有超级管理员，才能查看所有管理员列表
		if(userId != Constant.SUPER_ADMIN){
			params.put("createUserId", userId);
		}

		//查询列表数据
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		if(MapUtil.getStr(params,"key") != null){
			queryWrapper
					.like("username",MapUtil.getStr(params,"key"))
					.or()
					.like("mobile",MapUtil.getStr(params,"key"));
		}
		queryWrapper.eq("user_type", 2);
		queryWrapper.orderByDesc("create_time");
		IPage<SysUser> sysConfigList = sysUserService.page(mpPageConvert.<SysUser>pageParamConvert(params),queryWrapper);

		return R.ok().put("page", mpPageConvert.pageValueConvert(sysConfigList));
	}
	/**
	 * 医生列表
	 * @param params
	 * @return
	 */
	@RequestMapping("/docterList")
	public R docterList(@RequestParam Map<String, Object> params){
		//只有超级管理员，才能查看所有管理员列表
		SysUser user = getUser();
		//查询列表数据
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();

		if(user.getUserType()>3) {
			return R.ok();
		}
//		queryWrapper.eq("user_id", user.getUserId());
		
		if(MapUtil.getStr(params,"username") != null){
			queryWrapper
					.like("username",MapUtil.getStr(params,"username"));
					
		}
		if(MapUtil.getStr(params,"mobile") != null){
			queryWrapper.or()
			.like("mobile",MapUtil.getStr(params,"mobile"));
		}
		queryWrapper.eq("user_type", 3);
		queryWrapper.orderByDesc("create_time");
		IPage<SysUser> sysConfigList = sysUserService.page(mpPageConvert.<SysUser>pageParamConvert(params),queryWrapper);
		return R.ok().put("page", mpPageConvert.pageValueConvert(sysConfigList));
	}
	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public R info(){
		SysUser user = getUser();
		List <Long> roleIdList = sysRoleService.queryRoleIdList(user.getUserId());
		user.setRoleIdList(roleIdList);
		return R.ok().put("user",user );
	}
	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/docterInfo/{id}")
	public R docterInfo(@PathVariable("id") Long id){
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", id);
		SysUser docteruser = sysUserService.getOne(queryWrapper);
		return R.ok().put("user",docteruser);
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@RequestMapping("/password")
	public R password(String password, String newPassword){
		Assert.isBlank(newPassword, "新密码不为能空");
		
		//sha256加密
		password = new Sha256Hash(password, getUser().getSalt()).toHex();
		//sha256加密
		newPassword = new Sha256Hash(newPassword, getUser().getSalt()).toHex();
				
		//更新密码
		int count = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(count == 0){
			return R.error("原密码不正确");
		}
		
		return R.ok();
	}
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId){
		SysUser user = sysUserService.getById(userId);
		
		//获取用户所属的角色列表
//		List<Long> roleIdList = sysUserRoleService.list(
//				        new QueryWrapper<SysUserRole>()
//                        .lambda()
//                        .eq(SysUserRole::getUserId,userId)
//		        ).stream()
//                .map(sysUserRole ->sysUserRole.getRoleId())
//                .collect(Collectors.toList());
		
		List <Long> roleIdList = sysRoleService.getRoleIdListByUserId(userId);
		user.setRoleIdList(roleIdList);
		return R.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@RequestMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUser user){
		ValidatorUtils.validateEntity(user);
//		Collection<SysUserRole> newRoleList = new ArrayList<SysUserRole> ();
//		for (Long roleId : user.getRoleIdList()) {
//			SysUserRole sysUserRole = new SysUserRole();
//			sysUserRole.setRoleId(roleId);
//			sysUserRole.setUserId(user.getUserId());
//			newRoleList.add(sysUserRole);
//		}
		QueryWrapper< SysUser> userQueryWrapper = new QueryWrapper< SysUser>();
		userQueryWrapper.lambda().eq(SysUser::getMobile, user.getMobile()).or().eq(SysUser::getUsername, user.getMobile());
		Long existsCount = sysUserService.count(userQueryWrapper);
		if(existsCount>0) {
			return R.error(100001,"保存用户失败，原因：手机号为"+ user.getMobile()+"的用户已存在！");
		}
		user.setUserType(1);
		user.setUsername(user.getMobile());
		user.setPassword(user.getMobile());
		user.setCreateUserId(getUserId());
		user.setStatus(1);
		sysUserService.save(user);
		return R.ok();
	}
	
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUser user){
		ValidatorUtils.validateEntity(user);
		SysUser dbUser =  sysUserService.getById(user.getUserId());
		user.setCreateUserId(getUserId());
		Collection<SysUserRole> newRoleList = new ArrayList<SysUserRole> ();
		for (Long roleId : user.getRoleIdList()) {
			SysUserRole sysUserRole = new SysUserRole();
			sysUserRole.setRoleId(roleId);
			sysUserRole.setUserId(user.getUserId());
			newRoleList.add(sysUserRole);
		}
		QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
		queryWrapper.eq("user_id", user.getUserId());
		Collection<SysUserRole>oldRoleList =		sysUserRoleService.list(queryWrapper );
		for (SysUserRole sysUserRole : newRoleList) {
			if(sysUserRole.getId() == null ||!oldRoleList.contains(sysUserRole)) {
				sysUserRoleService.save(sysUserRole);
			}
		}
		for (SysUserRole sysUserRole2 : oldRoleList) {
			if(!newRoleList.contains(sysUserRole2)) {
				sysUserRoleService.removeById(sysUserRole2.getId());
			}
		}
		if(StringUtils.isNotBlank(user.getPassword()) ) {
			user.setPassword(new Sha256Hash(user.getPassword(), dbUser.getSalt()).toHex());
		}
		sysUserService.updateById(user);
		
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@RequestMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return R.error("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, getUserId())){
			return R.error("当前用户不能删除");
		}
		sysUserService.removeByIds(Arrays.asList(userIds));
		return R.ok();
	}
}
